package com.mrh.se2_contactasauraus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
	public final static String EXTRA_MESSAGE = "com.mrh.se2_contactasauraus.IDSent";
	int sendID = 0;
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.setting_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch(item.getItemId())
	    {
	    case R.id.add:
	    	//Clicked on add. Start new activity here
	    	Intent addIntent = new Intent(this,AddContact.class);
	    	addIntent.putExtra(EXTRA_MESSAGE,-1);
	    	startActivity(addIntent);
	    	return true;
	    	
	    case R.id.edit:
	    	Intent editIntent = new Intent(this,Edit_cat.class);
	    	startActivity(editIntent);
	    	return true;
	    case R.id.about:
	    	Intent aboutIntent = new Intent(this,About.class);
	    	startActivity(aboutIntent);
			return true;
		}
		return true;
	}

	private static final String TABLE_NAME = "contacts";
	private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME
			+ " (" + FeedEntry.COLUMN_NAME_ID + " INTEGER PRIMARY KEY, "
			+ FeedEntry.COLUMN_NAME_NAME + " TEXT, "
			+ FeedEntry.COLUMN_NAME_ADDRESS + " TEXT, "
			+ FeedEntry.COLUMN_NAME_CELL + " TEXT, "
			+ FeedEntry.COLUMN_NAME_ALT + " TEXT, "
			+ FeedEntry.COLUMN_NAME_EMAIL + " TEXT, "
			+ FeedEntry.COLUMN_NAME_COMMENTS + " TEXT,"
			+ FeedEntry.COLUMN_NAME_GROUP + " TEXT);";
	
	ArrayList<String> categories;

	// Prevents the FeedReaderContract class from being instantiated.
	private void FeedReaderContract() {
	}

	public static abstract class FeedEntry implements BaseColumns {
		public static final String TABLE_NAME = "contact";
		public static final String COLUMN_NAME_ID = "id";
		public static final String COLUMN_NAME_NAME = "name";
		public static final String COLUMN_NAME_ADDRESS = "address";
		public static final String COLUMN_NAME_CELL = "cell";
		public static final String COLUMN_NAME_ALT = "alt";
		public static final String COLUMN_NAME_EMAIL = "email";
		public static final String COLUMN_NAME_COMMENTS = "comment";
		public static final String COLUMN_NAME_GROUP = "group";
	}

	DatabaseHandler db;
	ArrayList<String> str;
	ArrayList<Contact> cc;
	
	// List view
	private ListView lv;

	// Listview Adapter
	ArrayAdapter<String> adapter;

	// Search EditText
	EditText inputSearch;

	// ArrayList for Listview
	ArrayList<HashMap<String, String>> productList;

	public void onResume() {
		categories = db.getAllCategories();
		str = new ArrayList<String>();
		Log.d("D", "We are resumed");
		//Check if back from deletion
		//Display delete confirm message
		this.onCreate(null);
	}
	
	public void populateContacts(ArrayList<Contact> l) {
		
		str.clear();
		
		cc = l;
		
		for (Contact cn : l) {
			String log = "Id: " + cn.getID() + " ,Name: " + cn.getName()
					+ " ,Phone: " + cn.getPhoneNumber();
//			// Writing Contacts to log
			Log.d("Name: ", log);
			str.add(cn.getDisplayName());
		}
		
		Log.d("pm", "populating main");
		adapter = new ArrayAdapter<String>(this, R.layout.list_item,
				R.id.product_name, str);
		lv.setAdapter(adapter);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Listview Data

		lv = (ListView) findViewById(R.id.list_view);
		inputSearch = (EditText) findViewById(R.id.inputSearch);
		db = new DatabaseHandler(this);
		

		Log.d("CC", "getting dem contacts");
		new GetAllContactsTask().execute(this);
			
		lv.setOnItemClickListener(new OnItemClickListener() {
		      public void onItemClick(AdapterView<?> parent, View view,
		          int position, long id) {
		    	  Intent addIntent = new Intent(MainActivity.this,AddContact.class);
			    	addIntent.putExtra(EXTRA_MESSAGE,cc.get(position).getID());
			    	startActivity(addIntent);
		      }
		});
		      
			inputSearch.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence cs, int arg1, int arg2,
						int arg3) {
					// When user cfhanged the Text
					ArrayList<Contact> contacts = null;
					
					
					
					
					if (cs.length() != 0) {
						Log.d("KK", cs.subSequence(0, Math.min(cs.length(), 4)).toString());
						if (cs.subSequence(0, Math.min(cs.length(), 4)).toString().equals("cat:") && cs.length() > 4) {
							Log.d("TTT", "Here");
							
							int i = -1;
							try {
								String catName = cs.subSequence(4, cs.length()).toString();
								if(catName.equals(categories.get(0)))
								{
									i = 0;
								}
								else if(catName.equals(categories.get(1)))
								{
									i = 1;
								}
								else if(catName.equals(categories.get(2)))
								{
									i = 2;
								}
								else if(catName.equals(categories.get(3)))
								{
									i = 3;
								}
								else if(catName.equals(categories.get(4)))
								{
									i = 4;
								}
//								i = Integer.parseInt(cs.subSequence(4, cs.length()).toString());
							} catch (Exception e) {
								e.printStackTrace();
							}
							new GetCatContactsTask().execute(i);
						} else
							new GetSearchContactsTask().execute(getApplicationContext(),cs.toString());
					} else {
						Log.d("C", "CS WAS 0");
						new GetAllContactsTask().execute(getApplicationContext());
					}
//					MainActivity.
					
				}



				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub
				}

//				public void onCreate(SQLiteDatabase db) {
//					db.execSQL(TABLE_CREATE);
//				}
			});
	}
	
	//performs database query outside GUI thread
	public class GetAllContactsTask extends AsyncTask<Context, Void, ArrayList<Contact>> {
		// perform the database access
		ArrayList<Contact> c;
		
		@Override
		protected ArrayList<Contact> doInBackground(Context... params) {
			DatabaseHandler databaseConnector = new DatabaseHandler(params[0]);
			// get a cursor containing all rows
			c = databaseConnector.getAllContacts();
			databaseConnector.close();
			return c;
		} // end method doInBackground
		
		@Override
		protected void onPostExecute(ArrayList<Contact> result)
		{
		// pass the result Cursor to where it is needed
		// …
			populateContacts(c);
		} // end method onPostExecute
		
		
	}
	
	public class GetSearchContactsTask extends AsyncTask<Object, Void, ArrayList<Contact>> {
		// perform the database access
		ArrayList<Contact> c;
		
		@Override
		protected ArrayList<Contact> doInBackground(Object... params) {
			DatabaseHandler databaseConnector = new DatabaseHandler((Context) params[0]);
			// get a cursor containing all rows
			c = databaseConnector.getSearchContacts((String) params[1]);
			databaseConnector.close();
			return c;
		} // end method doInBackground
		
		@Override
		protected void onPostExecute(ArrayList<Contact> result)
		{
		// pass the result Cursor to where it is needed
		// …
			populateContacts(c);
		} // end method onPostExecute

	}

	public class GetCatContactsTask	 extends AsyncTask<Integer, Void, ArrayList<Contact>> {
		// perform the database access
		ArrayList<Contact> c;
		
		@Override
		protected ArrayList<Contact> doInBackground(Integer... params) {
			DatabaseHandler databaseConnector = new DatabaseHandler(getApplicationContext());
			// get a cursor containing all rows
			c = databaseConnector.getCatContacts(params[0]);
			databaseConnector.close();
			return c;
		} // end method doInBackground
		
		@Override
		protected void onPostExecute(ArrayList<Contact> result)
		{
		// pass the result Cursor to where it is needed
		// …
			populateContacts(c);
		} // end method onPostExecute

	}
	
}
